<?php
/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2020/5/13
 * Time: 18:40
 */

namespace app\api\model;


use think\Cache;
use think\Model;

class Login extends Model
{
    protected $name = 'tb_admin';

    public function login($username, $password)
    {
        $user = $this->get(['Aname' => $username]);
        if (empty($user)){
            return ['token' => null, 'msg' => '用户不存在'];
        }
        if ($user['Apassword'] != $password) {
            return ['token' => null, 'msg' => '用户或密码不正确'];
        }
        $token = $this->token($user['Ano']);
        // 记录缓存, 7天
        Cache::set($token, $user['Ano'], 86400 * 7);

        return ['token' => $token, 'msg' => '登录成功', 'data' => $user];
    }

    public static function getUser($token)
    {
        $Eno = Cache::get($token);
        return self::get(['Ano' => $Eno]);
    }

    /**
     * 生成用户认证的token
     * @param $id
     * @return string
     */
    private function token($id)
    {
        $wxapp_id = 20200520;
        // 生成一个不会重复的随机字符串
        $guid = \getGuidV4();
        // 当前时间戳 (精确到毫秒)
        $timeStamp = microtime(true);
        // 自定义一个盐
        $salt = 'token_salt';
        return md5("{$wxapp_id}_{$timeStamp}_{$id}_{$guid}_{$salt}");
    }
}
